//
//  ScanDevViewController.m
//  AILock
//
//  Created by 谭亚明 on 2020/6/18.
//  Copyright © 2020 tym. All rights reserved.
//

#import "ScanDevViewController.h"
#import "ScanAnimationView.h"
#import "NoneDevView.h"
#import "NSString+SwitchData.h"
#import <NetworkExtension/NEHotspotConfigurationManager.h>
#import "NSString+WithCRCModbus.h"
#import "ShowAlertView.h"
#import "UserModel.h"
#import "FamilyModel.h"
#import "RoomSeleView.h"
#import "Sizes.h"
#import "EquipmentTypeModel.h"
#import "UserTool.h"
#import "EquipmentService.h"
#import "ScanResultVC.h"
#import "YYModel.h"
#import "UIView+ZFFrame.h"
#import "ESPTouchTask.h"
#import "AFNetworking.h"
#import "ESPTools.h"
#import <CocoaAsyncSocket/GCDAsyncSocket.h>
#import "NSString+SwitchData.h"
#import "NSData+SwitchData.h"

#define ESPTouchAppleID @"Apple ID"

#define XSIP   @"192.168.4.1"
#define XSPort 8266

@interface ScanDevViewController ()<GCDAsyncSocketDelegate>
{
    //AP配网
    GCDAsyncSocket * _asyncSocket;
}

@property(nonatomic,weak) ScanAnimationView *animationView;
@property(nonatomic,weak) NoneDevView *noneDev;

//samart配网
@property (atomic, strong) ESPTouchTask *_esptouchTask;
@property (nonatomic, strong) NSCondition *_condition;

@property(nonatomic,assign) NSUInteger scanAnimationCount;

@property(nonatomic,strong) EquipmentService *equService;
@end

@implementation ScanDevViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"设备扫描中"];
    [self initUI];
    self.tz_interactivePopDisabled = YES;
    self.scanAnimationCount = 0;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addEquipmentSuccess:) name:@"addEquipmentSuccess" object:nil];
}

-(void)backViewFunc:(id)btn{
    
    if([self.animationView isScaning]){
        [ShowAlertView showAlertViewTitle:@"提示" message:@"确定取消扫描吗" actionBtnTitle:@"确定"
                             hiddenCancel:NO
                               completion:^(NSInteger actionType) {
            if (actionType) {
                if (self._esptouchTask != nil)
                {
                    [self._esptouchTask interrupt];
                }
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//成功绑定设备的通知
-(void)addEquipmentSuccess: (NSNotification *) notification{
    
    EquipmentTypeModel *typeModel = [EquipmentTypeModel yy_modelWithJSON:notification.object];
    ScanResultVC *scanResultVc = [[ScanResultVC alloc] initWithEquipmentMode:typeModel];
    [self.navigationController pushViewController:scanResultVc animated:YES];
}

-(EquipmentService*)equService{
    if (_equService == nil) {
        _equService = [[EquipmentService alloc] init];
    }
    return _equService;
}

-(void)initUI{
    ScanAnimationView *view = [[ScanAnimationView alloc] initWithFrame:CGRectMake(ScreenWidth/2 - 133, NavigateonHeight, 266, 266+90)];
    [self.view addSubview:view];
    self.animationView = view;
    
    NoneDevView *noneView = [[NSBundle mainBundle]loadNibNamed:@"NoneDevView" owner:self options:nil].lastObject;
    [noneView setFrame:CGRectMake(0, ScreenHeight, ScreenWidth, 250)];
    noneView.seleActionBlock = ^(NSInteger index) {
        if (index) {
            self.scanAnimationCount = 0;
            [self.animationView starAnimation];
            [self animationTimeCountAdd];
            [self gotoConnectDev];
        }else{
            
        }
    };
    [self.view addSubview:noneView];
    self.noneDev = noneView;
}

-(void)gotoConnectDev{
    
    if (self.equipType.peiwangType == 0) {
        NSString *apSsid = [_netInfo objectForKey:@"ssid"];;
        NSString *apBssid = [_netInfo objectForKey:@"bssid"];
        int taskCount = 1;
        BOOL broadcast = YES;
        dispatch_queue_t  queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSArray *esptouchResultArray = [self executeForResultsWithSsid:apSsid bssid:apBssid password:self.passwordStr taskCount:taskCount broadcast:broadcast];
            dispatch_async(dispatch_get_main_queue(), ^{
                ESPTouchResult *firstResult = [esptouchResultArray objectAtIndex:0];
                if (!firstResult.isCancelled)
                {
                    [NSObject cancelPreviousPerformRequestsWithTarget:self];
                    self.scanAnimationCount = 0;
                    
                    if ([firstResult isSuc]) {
                        [self.animationView setSuccessStr:nil];
                        ESPTouchResult *resultModel = esptouchResultArray.firstObject;
                        [self addEqumentWithEqumentModel:resultModel];
                    }else {  //连接设备失败
                        [self.animationView stopAnimationScuess:NO];
                        [self.noneDev showNoneViewWithTop:self.animationView.zf_bottom - 50];
                    }
                }
            });
        });
    }else{
        if (self.equipType.peiwangType == 1) {
            [self wifiConnectAction];
        }
    }
}

//连接Wi-Fi的次数
int wifiConnect = 0;
-(void)wifiConnectAction{
    
    if (@available(iOS 11.0, *)) {
        NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:@"XSUN-LOCK"];
        [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
            if (error.code == NEHotspotConfigurationErrorAlreadyAssociated) {
                NSLog(@"+++++++++++++连接上西尚的无线");                   //已连接
                [self performSelector:@selector(connectAction) withObject:nil afterDelay:3.5];
                
            }else{
                if (wifiConnect < 5) {
                    wifiConnect++;
                    [self wifiConnectAction];
                    NSLog(@"++++++++++连接西尚的无线失败继续连接");
                }else{
                    NSLog(@"++++++++++连接西尚的无线失败");
                   // wifiConnect = 0;
                    
                    
                }
                
                
            }
        }];
    } else {
        // Fallback on earlier versions
    }
}

//新增设备  smart配网
-(void)addEqumentWithEqumentModel:(ESPTouchResult*)result{
    // TYMWeak(self);
    [self.equService getAddEquipmentWithType:self.equipType.typeValue macAddress:result.bssid ipAddress:[result getAddressString]  familyRoomId:nil familyId:[UserTool getCurrentFamily].familyId wifiName:self.netInfo[@"ssid"] completion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
        if (!response.error) {
        }else{
            [WHToast showMessage:response.message duration:2 finishHandler:nil];
        }
    }];
}

//AP配网新增设备
-(void)addEqumentAP:(id)bssID{
    
    [self.equService getAddEquipmentWithType:self.equipType.typeValue macAddress:bssID ipAddress:@" " familyRoomId:nil familyId:[UserTool getCurrentFamily].familyId wifiName:self.wifiName completion:^(NSError * _Nonnull error, LMJBaseResponse * _Nonnull response) {
        
        if(response.code == 0){
            NSLog(@"++++++++++++++++++++++++++添加设备成功");
            [WHToast showMessage:@"添加设备成功" duration:2 finishHandler:nil];
        }else{
            [self addEqumentAP:bssID];
        }
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    wifiConnect = 0;
    
    [self.animationView starAnimation];
    [self animationTimeCountAdd];
    [self gotoConnectDev];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
}

-(void)animationTimeCountAdd{
    if (self.scanAnimationCount > 99) {
        // AB配网
        if (self.equipType.peiwangType == 1) {
            [self.animationView stopAnimationScuess:NO];
            [self.noneDev showNoneViewWithTop:self.animationView.zf_bottom - 50];
            self.animationView.isLinkSc = NO;
            if ([_asyncSocket isConnected]) {
                [_asyncSocket disconnect];
            }
        }
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        return;
    }
    [self performSelector:@selector(animationTimeCountAdd) withObject:self afterDelay:1];
    self.scanAnimationCount++;
    [self.animationView setScanAnimationCount:self.scanAnimationCount];
}

#pragma mark - the example of how to use executeForResults
- (NSArray *) executeForResultsWithSsid:(NSString *)apSsid bssid:(NSString *)apBssid password:(NSString *)apPwd taskCount:(int)taskCount broadcast:(BOOL)broadcast
{
    [self._condition lock];
    self._esptouchTask = [[ESPTouchTask alloc]initWithApSsid:apSsid andApBssid:apBssid andApPwd:apPwd];
    [self._esptouchTask setPackageBroadcast:broadcast];
    [self._condition unlock];
    NSArray * esptouchResults = [self._esptouchTask executeForResults:taskCount];
    return esptouchResults;
}

//创建socket
-(void)connectAction{
   // if(_asyncSocket == nil){
        _asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    //}
    NSError * error = nil;
    [_asyncSocket connectToHost:XSIP onPort:XSPort  error:&error];
    if (error) {
        [self.animationView stopAnimationScuess:NO];
        [self.noneDev showNoneViewWithTop:self.animationView.zf_bottom - 50];
        NSLog(@"++++++++创建失败: %@", error.description);
    }else{
        NSLog(@"++++++++创建socket成功");
    }
}

//发送 03指令
-(void)sendCommendAction{
    
    NSString *strMsg = [self get03CommendWithWifiName:self.wifiName wifiPassword:self.passwordStr];
    [_asyncSocket writeData:[strMsg convertBytesStringToData] withTimeout:-1 tag:0];
}

// 根据wifi名称和密码返回 03指令字符串
-(NSString*)get03CommendWithWifiName:(NSString*)wifiName wifiPassword:(NSString*)password{
    NSInteger contentLength = wifiName.length + password.length + 7;
    NSString *str = @"585300";
    str = [str stringByAppendingFormat:@"%@03%@%@%@%@",[self toHex:contentLength],[self toHex:wifiName.length],[self toHex:password.length],[self hexStringFromString:wifiName],[self hexStringFromString:password]];
    NSString *crcStr = [str substringWithRange:NSMakeRange(4, str.length - 4)];
    str = [str stringByAppendingString:[[crcStr getCrcString] uppercaseString]];
    return  str;
}

//转16进制
-(NSString *) toHex:(long long int) num
{
    if (num < 10) {
        NSString * result = [NSString stringWithFormat:@"0%llx",num];
        return [result uppercaseString];
    }
    NSString * result = [NSString stringWithFormat:@"%llx",num];
    return [result uppercaseString];
}

//字符串转16进制
-(NSString *)hexStringFromString:(NSString *)string{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++)
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return [hexStr uppercaseString];
}


#pragma mark - AP配网的代理
- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"+++++++断开连接...%@", err.description);
    if (err.code == 60) {
        [self connectAction];
    }
    
}

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"+++++++已连接: %@, 端口: %d", host, port);
    
    [self sendCommendAction];
    
    [sock readDataWithTimeout:-1 tag:0];
}

NSString *macIp;
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (data) {
        NSString *recordStr = [NSString stringWithFormat:@"%@",[data dataToString]];
        
        NSArray *strArray = [recordStr componentsSeparatedByString:@","];
        NSArray *recordArray = [strArray subarrayWithRange:NSMakeRange(20, strArray.count - 20)];
        
        NSArray *macIPArray = [recordArray subarrayWithRange:NSMakeRange(6, recordArray.count - 8)];
        
        if (macIPArray.count == 6) {
            NSMutableArray *macArrar = [[NSMutableArray alloc] init];
            for (NSString *macip in macIPArray) {
                [macArrar addObject:[self toHex: [macip longLongValue]]];
            }
            macIp = [[macArrar componentsJoinedByString:@""] lowercaseString];
        }
        
        int commendID = [recordArray[4] intValue];
        int isSucces = [recordArray[5] intValue];
        
        if (commendID == 3) {
            //ap 配网接收成功
            if (isSucces == 1) {
                NSLog(@"+++++++++============ap 配网接收成功");
                self.animationView.isLinkSc = YES;
                self.scanAnimationCount = 0;
                
            }else{
                self.
                self.animationView.isLinkSc = NO;
                [self.animationView stopAnimationScuess:NO];
                [self.noneDev showNoneViewWithTop:self.animationView.zf_bottom - 50];
            }
        }else if(commendID == 4){
            
            if (isSucces == 1) {
                NSLog(@"++++++++++++++++++++++++++++路由器连接成功");
                
                if(@available(iOS 11.0, *)){
                    [[NEHotspotConfigurationManager sharedManager] removeConfigurationForSSID:@"XSUN-LOCK"];
                }
                
                if (@available(iOS 11.0, *)) {
                    
                    NEHotspotConfiguration * hotspotConfig = [[NEHotspotConfiguration alloc] initWithSSID:self.wifiName passphrase:self.passwordStr isWEP:NO];
                    [[NEHotspotConfigurationManager sharedManager] applyConfiguration:hotspotConfig completionHandler:^(NSError * _Nullable error) {
                        if (!error) {
                            NSLog(@"++++++++++++++++++切换正常网络成功");
                            [self performSelector:@selector(addEqumentAP:) withObject:macIp  afterDelay:10];
                        }

                    }];
                }
            }else{// 连接超时
                NSLog(@"+++++++++++++++返还超时");
                self.animationView.isLinkSc = NO;
                [self.animationView stopAnimationScuess:NO];
                [self.noneDev showNoneViewWithTop:self.animationView.zf_bottom - 50];
            }
        }
    }
    
    [sock readDataWithTimeout:-1 tag:tag];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"已发送Tag: %ld", tag);
    
    [sock readDataWithTimeout:-1 tag:tag];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addEquipmentSuccess" object:nil];
    
    NSLog(@"+++++++++++++++++++释放ScanDeviewController");
}


@end
